package com.wyj.controller;

import com.wyj.pojo.DiscussPost;
import com.wyj.pojo.Page;
import com.wyj.service.imp.ElasticsearchServiceImp;
import com.wyj.service.imp.LikeServiceImp;
import com.wyj.service.imp.UserServiceImp;
import com.wyj.util.CommunityConstant;
import org.elasticsearch.index.engine.Engine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 王永杰
 * @Description 描述该类的做什么用
 * @since 2022/8/7
 */
@Controller
public class ElstaticSearchController implements CommunityConstant {

    @Autowired
    ElasticsearchServiceImp elasticsearchServiceImp;

    @Autowired
    UserServiceImp userServiceImp;

    @Autowired
    LikeServiceImp likeServiceImp;

    @RequestMapping(value = "/search",method = RequestMethod.GET)
    public String getSearch(String keyword, Page page, Model model) {

        //搜索帖子
        org.springframework.data.domain.Page<DiscussPost> discussPosts = elasticsearchServiceImp.searchDiscussPost(keyword, page.getCurrent() - 1, page.getLimit());

        //设置分页
        page.setPath("/search?keyword="+keyword);
        page.setRows(discussPosts != null ? discussPosts.getTotalPages():0);

        List<Map<String,Object>> listPost = new ArrayList<>();

        //聚合数据
        if (discussPosts != null) {
            for (DiscussPost discussPost : discussPosts) {
                Map<String,Object> map = new HashMap<>();
                //存帖子
                map.put("post",discussPost);
                //存作者
                map.put("user",userServiceImp.getUserById(discussPost.getUserId()));
                //存点赞数
                map.put("likeCount",likeServiceImp.findEntityLikeCount(ENTITY_TYPE_POST,discussPost.getId()));
                listPost.add(map);
            }
        }

        model.addAttribute("listPost",listPost);

        return "site/search";
    }
}
